package cn.virens.packet.handler;

import org.tio.core.ChannelContext;
import org.tio.server.ServerGroupContext;

import cn.virens.App;
import cn.virens.TioUtil;
import cn.virens.app.common.BytesBuilder;
import cn.virens.app.common.SQL;
import cn.virens.common.ByteUtil;
import cn.virens.packet.ReadPacket;
import cn.virens.packet.WritePacket;

public class LoginHandler extends AbstractHandler {
	protected ServerGroupContext serverGroupContext;

	@Override
	public void read(ReadPacket packet, ChannelContext channelContext) {
		logger.debug("接收登录包");
		TioUtil.heartTimes(channelContext, (t) -> t.incrementAndGet());
		TioUtil.heartIdle(channelContext, (t) -> t.getAndSet(0));

		String imsi = ByteUtil.toAscii(packet.data(2, 15));
		//检查是否已经有连接
		ChannelContext channelContext1 = App.device().channelGet(imsi);
		if (channelContext1 != null) {
			logger.debug("设备--->{}已有连接，开始断开连接，准备重新连接", imsi);
			App.device().channelReconnect(channelContext1, channelContext);
		}

		// 绑定设备版本 & 设备IMEI
		App.device().channelbind(channelContext, imsi);
		App.device().channelbindVer(channelContext, packet.ver());

		//解析数据包
		String iccid = ByteUtil.toAscii(packet.data(17, 20));//iccid0
		Integer csq = ByteUtil.toInt(packet.data(47, 1));//信号

		//登录连接成功
		App.db().executeUpdate(SQL.ON_LINE, imsi, iccid, csq, csq, imsi);
		App.db().executeUpdate(SQL.ONLINE_STATUS_UP, 1, imsi);
		App.db().executeUpdate(SQL.ONLINE_STATUS_DE, imsi);
		App.db().executeUpdate(SQL.RECORD_IN, imsi, 1, "设备正常上线（登录）");

		//构建应答包数据
		BytesBuilder builder = new BytesBuilder();
		builder.append(ByteUtil.toByte((int) (System.currentTimeMillis() / 1000), 4));

		WritePacket writePacket = WritePacket.of(packet, "8000");
		writePacket.data(builder.toArray());

		//发送应答包
		TioUtil.write(channelContext, writePacket);
	}

}
